<?php

namespace app\api\controller;

use app\common\AudioFileAllOperation;
use think\Db;
use app\common\extract\Word;
use app\common\cache\RedisPackage;

class Recorderpen
{
    //文件上传
    public function audioUpload()
    {
        try {
            Db::startTrans();
            $param = input('param.');
            //根据文件id，获取文件名
            $file_model = Model('LiveSpeech1')->get(['filename' => $param['filename']]);
            //$path = config('share_path') . config('huisheng.recorder_pen_file_path') . DS . $file_model->filename;
            $path = config('huisheng.base_dir') . config('huisheng.recorder_pen_file_path') . DS . $file_model->filename;
            $param['path'] = $path;
            $data = [
                'timestamp' => time(),
                'status' => 2,
                'message' => "文件上传未成功"
            ];
            if (is_file($path)) {
                $param['timestamp'] = $data['timestamp'];
                $param['formatname'] = md5(date('YmdHis', $data['timestamp']));
                $this->createData($file_model, $param);
                $this->transPush($file_model);
                //$result = $this->handler($path, $param['formatname'], 0);
                //$this->updateData($file_model, $result['seconds']);
                //$this->offPush($file_model);
                Db::commit();
                $data['status'] = 1;
                $data['message'] = "文件开始转写";
                $data['fileid'] = $file_model->id;
            }
        } catch (\Exception $e) {
            Db::rollback();
            $data['status'] = 2;
            //$data['message'] = $e->getMessage();
            $data['message'] = "请求失败";
        } finally {
            return resultArray(['data' => $data]);
        }
    }

    //转写预备工作
    private function handler($in_path, $out_path, $uid)
    {
        $out_path = config('huisheng.box_audio_dir') . DS . pathinfo($out_path)['filename'] . ".wav";
        AudioFileAllOperation::moveFileandTrans2Wav($in_path, $out_path);
        $seconds = AudioFileAllOperation::waveDetailLength($out_path);
        if (!is_dir(config('huisheng.upload_mp3_path') . DS . $uid)) {
            mkdir(config('huisheng.upload_mp3_path') . DS . $uid, 0777, true);
        }
        $mp3_path = config('huisheng.upload_mp3_path') . DS . $uid . DS . pathinfo($in_path)['filename'] . ".mp3";
        AudioFileAllOperation::wavTrans2Another($out_path, $mp3_path);
        $json_path = config('huisheng.upload_mp3_path') . DS . $uid . DS . pathinfo($in_path)['filename'] . ".json";
        AudioFileAllOperation::wave2json($out_path, $json_path, $seconds);
        return ['out_path' => $out_path, 'seconds' => $seconds];
    }

    //创建文件数据 
    private function createData($file_model, $data)
    {
        //更新主表
        $file_model->formatname = $data['formatname'];
        $file_model->size = @filesize($data['path']) ?: 0;
        $file_model->update_time = $data['timestamp'];
        $file_model->transition_state = 1;
        $file_model->save();
        //插入另一个表
        $params = [
            //'meeting_id' => $file_model->id,
            'device_id' => $file_model->did,
            'filename' => $file_model->filename,
            'user_id' => 0,
            'formatname' => pathinfo($data['formatname'])['filename'] . ".wav",
            'create_time' => $data['timestamp'],
            'update_time' => $data['timestamp'],
            'lvsr_status' => 0
        ];
        $file_model->oneSpeech()->save($params);
    }

    //文件初始化后 更新
    private function updateData($file_model, $seconds)
    {
        //开始记录转写结束时候的状态
        $param = [
            //'lid' => $mid,
            'last_vad_name' => '',
            'is_end_speech' => 1,
            'vad_count' => 1
        ];
        $file_model->liveDetail->save($param);
        //更新主表音频时长
        $file_model->seconds = $seconds;
        $file_model->save();
        //更新附表状态
        $file_model->oneSpeech->lvsr_status = 1;
        $file_model->oneSpeech->save();
        return true;
    }

    //插入格式转换队列
    public function transPush($file_model)
    {
        $redis = RedisPackage::getInstance();
        $push_array = [
            'type' => 2,
            'id' => $file_model->id,
            'ori_path' => config('huisheng.base_dir') . config('huisheng.recorder_pen_file_path') . DS . $file_model->filename,
            'des_path' => config('huisheng.box_audio_dir') . DS . $file_model->formatname . ".wav",
        ];
        $redis->pushUploadFileQueue($push_array);
    }

    //插入转写文件队列
    public function offPush($file_model)
    {
        $redis = RedisPackage::getInstance();
        $arr = [
            'id' => $file_model->id,
            'file' => $file_model->formatname . '.wav',
        ];
        $redis->offTransPush($arr);
    }

    //创建文件数据 废弃
    // private function createData($data)
    // {
    //     $param = [
    //         'uid' => 0,
    //         'did' => 0,
    //         'filename' => $data['filename'],
    //         'formatname' => $data['formatname'],
    //         'size' => @filesize($data['path']) ?: 0,
    //         'create_time' => $data['timestamp'], 'update_time' => $data['timestamp'], 'start_time' => $data['timestamp'],
    //         'is_manual' => 1,
    //         'transition_state' => 1,
    //         'meeting_tag' => 'recorder-' . md5($data['filename'] . time())
    //     ];
    //     $result_live_id = Model('LiveSpeech1')->createFileData($param);
    //     //插入另一个表
    //     $params = [
    //         'meeting_id' => $result_live_id,
    //         'device_id' => 0,
    //         'filename' => $param['filename'],
    //         'user_id' => 0,
    //         'formatname' => pathinfo($param['formatname'])['filename'] . ".wav",
    //         'create_time' => $data['timestamp'],
    //         'update_time' => $data['timestamp'],
    //         'lvsr_status' => 0
    //     ];
    //     $result_speech_id = Model('Speech')->data($params)->allowField(true)->save();
    //     return $result_live_id;
    // }

    //文件初始化后 更新 废弃
    // private function updateData($mid, $seconds)
    // {
    //     //开始记录转写结束时候的状态
    //     $param = [
    //         'lid' => $mid,
    //         'last_vad_name' => '',
    //         'is_end_speech' => 1,
    //         'vad_count' => 1
    //     ];
    //     $live_id = Model('LiveSpeech1')->get($mid);
    //     $res_t = $live_id->save(['seconds' => $seconds]);
    //     $res = Model('LiveDetail')->data($param)->save();
    //     //$res_live = Model('LiveSpeech1')->get($mid)->save(['seconds' => $seconds]);
    //     $res_speech = Model('Speech')->get(['meeting_id' => $mid])->save(['lvsr_status' => 1]);
    //     return true;
    // }

    public function getSpeechResult()
    {
        try {
            $param = input('param.');
            $data = [
                'status' => 2,
                'type' => 1
            ];
            $live_model = Db::name('meeting_live_speech')->where(['id' => $param['fileid']])->find();
            if ($live_model['transition_state'] == 2) {
                $data['result'] = json_decode($live_model['transfer'], true);
                $data['create_time'] = $live_model['create_time'];
                $data['update_time'] = $live_model['update_time'];
                $data['status'] = 1;
            }
            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            $data['status'] = 3;
            //$data['message'] = $e->getMessage();
            $data['message'] = '请求失败';
            return resultArray(['data' => $data]);
        }
    }

    //创建文档
    public function getDownloadTxtPath()
    {
        try {
            $args = ['title' => '', 'time' => '', 'address' => '', 'host' => '', 'record' => '', 'name' => '', 'remark' => '', 'data' => ''];
            $args['data'] = input('param.data');
            $filename = md5(microtime());
            $result = (new Word())->template2File($filename, $args);
            cache($filename, $result, 60 * 60 * 24);
            return resultArray(['data' => ['path' => $filename]]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    /**
     * 
     */
    public function downloadFile($path)
    {
        download_result_one(cache($path));
    }

    /**
     * 新接口 获取用户设备非实时录音列表
     */
    public function offTransList()
    {
        $param = input('param.');
        $result = Db::name('meeting_live_speech')
            ->where(['uid' => $param['user_id'], 'did' => $param['device_id'], 'is_manual' => 2])
            ->field('id,transition_state as status')->select();
        return resultArray(['data' => ['list' => $result]]);
    }

    //
    public function transFileList($file_id = []){
        $result = Db::name('meeting_live_speech')->where('id', 'in', json_decode($file_id,true))->field('id,transition_state as status,is_manual as manual')->select();
        return resultArray(['data' => ['list' => $result, 'count' => count($result)]]);
    }

    /**
     * 获取反馈信息接口
     */
    public function suggestion($user_id=0,$type='',$describe,$phone)
    {
        try {
            $field = [
                'uid' => $user_id,
                'type' => $type,
                'describe' => $describe,
                'phone' => $phone,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $result_id = Db::name('suggestion')->insertGetId($field);

            $content =  "问题类型：" . $type . "\r\n<br>" . "问题描述：" . $describe . "\r\n<br>" . "联系方式：" . $phone;
            $data = [
                'title' => '意见反馈',
                'send_email' => 'asrupload@raisound.com',
                'content' => $content
            ];
            //发送邮件
            sendEmail($data);
            return resultArray(['data' => ['status' => 1,'message' => '发送成功']]);
        } catch (\Exception $e) {
            Db::name('suggestion')->where(['id'=>$result_id])->update(['status' => 2]);
            return resultArray(['data' => ['status' => 2,'message' => '发送失败']]);
        }
    }
}
